﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using EasyIot.Common;
using EasyIot.WebApp.Common;
using EasyIot.WebApp.Controllers;

namespace EasyIot.WebApp
{
    public class HandlerLoginAttribute : Attribute, IActionFilter
    {
        public bool Ignore = true;

        public HandlerLoginAttribute(bool ignore = true)
        {
            Ignore = ignore;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (Ignore == false)
            {
                return;
            }

            if (context.Controller is not BaseController)
            {
                return;
            }

            var operatorModel = new OperatorProvider(context.HttpContext).GetCurrent();
            if (null == operatorModel)
            {
                ContentResult Content = new ContentResult();
                Content.Content = "<script>top.location.href='/Login/Index';</script>";
                Content.ContentType = "text/html";
                context.Result = Content;
            }
            else
            {
                string roleModules = operatorModel.RoleModules.ToLower();
                var bases = context.HttpContext.Request;
                string url = bases.Path.ToString().ToLower();

                if (url.Contains("/home") || url.Contains("/permissions/module") || url.Contains("/permissions/roleauthorize/insertbatch"))
                {
                    return;
                }

                string rootUrl = url;
                string[] item = url.Split('/'); if (item.Length > 3) rootUrl = "/" + item[1] + "/" + item[2];

                if (!string.IsNullOrEmpty(roleModules) && !roleModules.Contains(rootUrl))
                {
                    ContentResult Content = new ContentResult();
                    Content.Content = "<script>window.location.href='/Exception/Index?error=抱歉，你没有查看该功能项权限';</script>";
                    Content.ContentType = "text/html";
                    context.Result = Content;
                }
            }
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            //if (context.Result?.GetType() == typeof(JsonResult))
            //{
            //    JsonResult result = context.Result as JsonResult;
            //    JObject valueObject = (JObject)(result.Value);
            //    valueObject["xb"] = "xxxx";
            //    result.Value = valueObject;
            //    context.Result = result;
            //    string yy = "";
            //}
        }
    }
}